<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of dbquery
 *
 * @author user
 */
class DBQuery {

    //put your code here
    protected $_db;
    protected $_result;
    private static $instance;

    public function __construct() {
        $this->_db = & Database::handler();
        self::$instance = $this;
    }

    public static function instance() {
        return self::$instance;
    }

    /**
     * Send query to mysql.
     * If query is 'select', this function will return array
     *
     * @param   string  query
     * @param   boolean single result
     * @return  mixed
     */
    function query($query, $single_result = FALSE) {
        $this->_result = mysql_query($query, $this->_db);

        if (preg_match("/select/i", $query)) {
            if ($this->_result === FALSE) {
                show_error("error query : " . $query);
            }
            $result = array();
            $table = array();
            $field = array();
            $temp_results = array();
            $num_of_fields = mysql_num_fields($this->_result);

            for ($i = 0; $i < $num_of_fields; ++$i) {
                array_push($table, mysql_field_table($this->_result, $i));
                array_push($field, mysql_field_name($this->_result, $i));
            }

            while ($row = mysql_fetch_row($this->_result)) {
                for ($i = 0; $i < $num_of_fields; ++$i) {
                    $temp_results[$table[$i]][$field[$i]] = $row[$i];
                }

                if ($single_result === TRUE) {
                    mysql_free_result($this->_result);
                    return $temp_results;
                }

                array_push($result, $temp_results);
            }

            mysql_free_result($this->_result);
            return ($result);
        }

        return $this->_result;
    }

}

?>
